/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.service.impl;


import com.google.gson.Gson;
import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.util.DocConverterUtils;
import com.koron.common.web.Util;
import com.koron.scene.domain.HealthCheck;
import com.koron.scene.mapper.HealthCheckMapper;
import com.koron.scene.service.api.HealthCheckService;
import com.koron.scene.utils.BusinessCode;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class HealthCheckServiceImpl implements HealthCheckService {

    private final static  Logger logger = LoggerFactory.getLogger(HealthCheckServiceImpl.class);

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private DocConverterUtils docConverterUtils;

    @Autowired
    private Util util;

    @Override
    public DataBean<HealthCheck> fetchHealths(String corpCode, String staffName, String deptName, Date beginTime, Date endTime, Integer start, Integer rows) {
        if (logger.isDebugEnabled()) {
            logger.debug("staffName = {}, deptName = {}", staffName, deptName);
        }
        try (SessionFactory factory = new SessionFactory()) {
            HealthCheckMapper mapper = factory.getMapper(HealthCheckMapper.class);
            List<HealthCheck> healthList = mapper.queryByCondition(corpCode, staffName, deptName, beginTime, endTime, start, rows);
            Integer total = mapper.countByCondition(corpCode, staffName, deptName, beginTime, endTime);
            DataBean<HealthCheck> dataBean = new DataBean<>();
            dataBean.setList(healthList);
            dataBean.setPageSize(rows);
            dataBean.setTotalNumber(total);
            dataBean.setTotalPage(total > rows ? (total % rows == 0 ? total / rows : total / rows + 1) : 1);
            dataBean.setPageNo(start / rows + 1);
            return dataBean;
        }
    }

    @Override
    public HealthCheck fetchOne(String id) {
        if (logger.isDebugEnabled()) {
            logger.debug("id = {}", id);
        }
        try (SessionFactory factory = new SessionFactory()) {
            return factory.getMapper(HealthCheckMapper.class).queryOne(id);
        }
    }

    @Override
    public Boolean batchDetele(List<String> idList) {
        try (SessionFactory factory = new SessionFactory()) {
            return factory.getMapper(HealthCheckMapper.class).batchDetele(idList) >= 0;
        }
    }

    @Override
    public MessageBean persist(HealthCheck health, MultipartFile[] files, String delFileAddress, String keepFileAddress, String delPreFileAddress, String keepPreFileAddress) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        // 参数校验
        if (StringUtils.isEmpty(health.getCorpCode())) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        if (StringUtils.isEmpty(health.getStaffCode()) || StringUtils.isEmpty(health.getStaffName())) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription("人员信息不能为空");
            return msg;
        }
        if (StringUtils.isEmpty(health.getJobs())) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription("岗位工种不能为空");
            return msg;
        }
        if (health.getCheckTime() == null) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription("体检日期不能为空");
            return msg;
        }
        if (health.getNextTime() == null) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription("下次体检日期不能为空");
            return msg;
        }
        if (health.getOccupationalDisease() == null) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription("是否有职业病不能为空");
            return msg;
        }
        List<String> addAddressList = new ArrayList<>();
        List<String> addPreAddressList = new ArrayList<>();
        List<String> keepAddressList = new ArrayList<>();
        List<String> keepPreAddressList = new ArrayList<>();
        try (SessionFactory factory = new SessionFactory()) {
            String[] keepAddressArray = StringUtils.isBlank(keepFileAddress) ? null : keepFileAddress.split("[,，]");
            if (keepAddressArray != null && keepAddressArray.length > 0) {
                keepAddressList.addAll(Arrays.asList(keepAddressArray));
            }
            String[] keepPreAddressArray = StringUtils.isBlank(keepPreFileAddress) ? null : keepPreFileAddress.split("[,，]");
            if (keepPreAddressArray != null && keepPreAddressArray.length > 0) {
                keepPreAddressList.addAll(Arrays.asList(keepPreAddressArray));
            }
            // 上传图片
            if (null != files) {
                for (MultipartFile file : files) {
                    String url = clientWrapper.uploadFile(file);
                    String filpath = url + "#" + file.getOriginalFilename();
                    addAddressList.add(filpath);
                    String filePrePath = docConverterUtils.converterUpdate(file);
                    if (filePrePath != null) {
                        addPreAddressList.add(filePrePath);
                    } else {
                        addPreAddressList.add(filpath);
                    }
                }
                keepAddressList.addAll(addAddressList);
                keepPreAddressList.addAll(addPreAddressList);
            }
            health.setAttachment(keepAddressList.size() <= 0 ? null : new Gson().toJson(keepAddressList));
            health.setPreviewAttachment(keepPreAddressList.size() <= 0 ? null : new Gson().toJson(keepPreAddressList));
            HealthCheckMapper mapper = factory.getMapper(HealthCheckMapper.class);
            if (StringUtils.isBlank(health.getId())) {
                health.setId(DefaultIdGenerator.getInstance().generateLongId());
                if (mapper.insert(health) > 0) {
                    return msg;
                }
            } else {
                if (mapper.update(health) > 0) {
                    if (StringUtils.isNotBlank(delFileAddress)) {
                        String[] delArray = delFileAddress.split("[,，]");
                        removeAttachment(Arrays.asList(delArray));
                    }
                    if (StringUtils.isNotBlank(delPreFileAddress)) {
                        String[] delArray = delPreFileAddress.split("[,，]");
                        removeAttachment(Arrays.asList(delArray));
                    }
                    return msg;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            removeAttachment(addAddressList);
            removeAttachment(addPreAddressList);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            logger.error(e.getMessage(),e);
        }
        return msg;
    }

    @Override
    public List<HealthCheck> exportList(StaffBean user, String corpCode, String staffName, String deptName, Date beginTime, Date endTime) {
        if (logger.isDebugEnabled()) {
            logger.debug("staffName = {}, deptName = {}", staffName, deptName);
        }
        try (SessionFactory factory = new SessionFactory()) {
            HealthCheckMapper mapper = factory.getMapper(HealthCheckMapper.class);
            List<HealthCheck> healthList = mapper.queryByCondition(corpCode, staffName, deptName, beginTime, endTime, null, null);
            if (null != healthList && healthList.size() > 0) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                healthList.forEach(bean->{
                    if (StringUtils.isNotEmpty(bean.getCorpCode())) {
                        List<DepartmentTreeBean> departmentTreeBeanList = (List<DepartmentTreeBean>) util.depttree(bean.getCorpCode(), 0).getData();
                        Map<String, String> map = departmentTreeBeanList.stream().collect(Collectors.toMap(DepartmentTreeBean::getDepartmentCode, DepartmentTreeBean::getName));
                        bean.setCorpName((departmentTreeBeanList == null || departmentTreeBeanList.size() <= 0)
                                ? null : map.get(bean.getCorpCode()));
                    }
                    if (null != bean.getCheckTime()) {
                        bean.setCheckTimeStr(sdf.format(bean.getCheckTime()));
                    }
                    if (null != bean.getNextTime()) {
                        bean.setNextTimeStr(sdf.format(bean.getNextTime()));
                    }
                });
            }
            return healthList;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    private void removeAttachment(List<String> delFileAddress) {
        if (delFileAddress != null && !delFileAddress.isEmpty()) {
            for (String delAdr : delFileAddress) {
                clientWrapper.deleteFile(delAdr.split("#")[0]);
            }
        }
    }

}
